from collections.abc import Iterable, Iterator


# 列表是可迭代对象，但不是迭代器
numbers = [1, 2, 3]
# print(isinstance(numbers, Iterable))  # True
# print(isinstance(numbers, Iterator))  # False


# print(isinstance(reversed(numbers), Iterator))

# 将列表numbers通过iter()转换成迭代器
convert_numbers_into_iter = iter(numbers)


print(type(convert_numbers_into_iter))  # <class 'list_iterator'>

for i in range(len(numbers)):
    print(
        "调用迭代器的__next__方法，遍历迭代器中的每一项=",
        convert_numbers_into_iter.__next__(),
    )

# 迭代器在上面消耗完，不能再调用__next__方法

try:
    print(convert_numbers_into_iter.__next__())
except StopIteration as e:
    print("迭代器已经用完了，不能再被迭代", e)


class MyIterator:

    def __init__(self, data):
        self.data = data
        self.index = 0

    def __iter__(self):
        """返回自身"""
        return self

    def __next__(self):
        """返回下一个元素"""
        if self.index >= len(self.data):
            raise StopIteration

        value = self.data[self.index]
        self.index += 1
        return value


# 使用自定义迭代器
my_iterator = MyIterator([1, 2, 3])


first_data = my_iterator.__next__()
print("first_data===", first_data)

second_data = next(my_iterator)

print("second_data===", second_data)
